package need_learn.coding.haoweilai;

import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson.JSONArray;
/**
 * TODO 好未来，写一个校验Json 数据的方法，要求能够输出不匹配项
 *
 * @author david
 * @version 1.0
 * @date 2021/4/20 14:56
 */
public class fastJsonDiff {
    public static void compareJson(JSONObject json1, JSONObject json2) {
        for (String s : json1.keySet()) {
            compareJson(json1.get(s), json2.get(s), s);
        }
    }

    public static void compareJson(Object json1, Object json2, String key) {
        if (json1 instanceof JSONObject) {
            compareJson((JSONObject) json1, (JSONObject) json2);
        } else if (json1 instanceof JSONArray) {
            compareJson((JSONArray) json1, (JSONArray) json2, key);
        } else if (json1 instanceof String) {
            try {
                String json1ToStr = json1.toString();
                String json2ToStr = json2.toString();
                compareJson(json1ToStr, json2ToStr, key);
            } catch (Exception e) {
                System.out.println("转换发生异常 key:" + key);
                e.printStackTrace();
            }
        } else {
            compareJson(json1.toString(), json2.toString(), key);
        }

    }

    public static void compareJson(String str1, String str2, String key) {
        if (!str1.equals(str2)) {
            System.err.println("不一致key:" + key + ",json1:" + str1 + ",json2:" + str2);
        } else {
            System.out.println("一致：key:" + key + ",json1:" + str1 + ",json2:" + str2);
        }

    }

    public static void compareJson(JSONArray json1, JSONArray json2, String key) {
        if (json1 != null && json2 != null) {
            int j1 = json1.size();
            int j2 = json2.size();
            if (j1 > j2) {
                j1 = j2;
            }
            for (int i = 0; i < j1; i++) {
                compareJson(json1.get(i), json2.get(i), key);
            }
        } else {
            if (json1 == null && json2 == null) {
                System.err.println("不一致：key:" + key + " 在json1和json2中均不存在");
            } else if (json1 == null) {
                System.err.println("不一致：key:" + key + " 在json1中不存在");
            } else {
                System.err.println("不一致：key:" + key + " 在json2中不存在");
            }
        }
    }

    private final static String st1 = "{\"username\":\"tom\",\"age\":18,\"address\":[{\"province\":\"上海市\"},{\"city\":\"上海市\"},{\"distinct\":\"静安区\"}]}";

    private final static String st2 = "{username:\"tom\",age:18}";

    public static void main(String[] args) {
        System.out.println(st1);
        System.out.println(st2);

        JSONObject jsonObject1 = JSONObject.parseObject(st1);
        JSONObject jsonObject2 = JSONObject.parseObject(st2);

        compareJson(jsonObject1, jsonObject2);

    }

}